<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8" />
    <title>AI聊天助手</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
            background: #f2f2f2;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            background-attachment: fixed;
            background-image: url('./images/backgroud-ai.jpg');
            position: relative;
            height: 100vh;
            overflow: hidden;
        }

        body::before {
            content: "";
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.4); /* 黑色半透明遮罩 */
            z-index: -1;
        }

        /* 整个页面的滚动条 */
        ::-webkit-scrollbar {
            width: 8px;
            /* 更窄的垂直滚动条 */
            height: 8px;
            /* 更窄的水平滚动条 */
        }

        /* 滚动条轨道 */
        ::-webkit-scrollbar-track {
            background: #f5f5f5;
            /* 非常浅的灰色轨道 */
            border-radius: 4px;
        }

        /* 滚动条滑块 */
        ::-webkit-scrollbar-thumb {
            background: #d0d0d0;
            /* 浅灰色滑块 */
            border-radius: 4px;
            border: 2px solid #f5f5f5;
            /* 更窄的边框 */
        }

        /* 鼠标悬停时的滚动条滑块 */
        ::-webkit-scrollbar-thumb:hover {
            background: #b0b0b0;
            /* 悬停时稍深的灰色 */
        }

        .header-title {
            color: white;
            text-align: center;
            margin-bottom: 20px;
            text-shadow: 0 2px 4px rgba(0,0,0,0.5);
            font-size: 28px;
        }

        #container {
            display: flex;
            width: 1200px;
            height: calc(100vh - 100px);
            background: rgba(255, 255, 255, 0.95);
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            margin: 0 auto;
            overflow: hidden;
        }


        #sidebar {
            width: 250px;
            background: #f5f5f5;
            border-right: 1px solid #ddd;
            display: flex;
            flex-direction: column;
            padding: 20px 0;
        }

        #new-session-btn {
            margin: 0 20px 20px;
            padding: 12px;
            background: #4caf50;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
        }

        #new-session-btn:hover {
            background: #45a049;
        }

        #config-btn {
            margin: 0 20px 20px;
            padding: 12px;
            background: #2196F3;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
        }

        #config-btn:hover {
            background: #1976D2;
        }

        #sessions-list {
            flex: 1;
            overflow-y: auto;
        }

        .session-item {
            padding: 12px 20px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
            transition: background 0.2s;
        }

        .session-item:hover {
            background: #e9e9e9;
        }

        .session-item.active {
            background: #e0e0e0;
            font-weight: bold;
        }

        .session-item-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .session-item-name {
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .session-item-delete {
            background: none;
            border: none;
            color: #888;
            cursor: pointer;
            font-size: 18px;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }

        .session-item-delete:hover {
            background: #ddd;
            color: #f44336;
        }

        .session-item-date {
            font-size: 12px;
            color: #888;
            margin-top: 4px;
        }

        .session-rename-input {
            flex: 1;
            border: 1px solid #4caf50;
            border-radius: 4px;
            padding: 4px 8px;
            font-size: 14px;
            outline: none;
            background: white;
        }

        #main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            position: relative;
        }

        #chat {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            line-height: 1.6;
        }

        .message {
            margin-bottom: 15px;
            padding: 12px 15px;
            border-radius: 10px;
            word-wrap: break-word;
            word-break: break-word;
            animation: fadeIn 0.3s ease-in;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .user {
            background-color: #e3f2fd;
            color: #1976d2;
            text-align: right;
            margin-left: 20%;
        }

        .assistant {
            background-color: #f5f5f5;
            color: #333;
            margin-right: 20%;
        }

        #inputArea {
            display: flex;
            padding: 15px;
            background: white;
            border-top: 1px solid #eee;
            width: 100%;
            position: relative;
            bottom: 0;
        }

        #prompt {
            flex: 1;
            font-size: 16px;
            padding: 12px 60px 12px 20px; /* 右侧留出按钮空间 */
            border: 2px solid #e0e0e0;
            border-radius: 30px;
            outline: none;
            transition: all 0.3s ease;
            height: 100px;
            resize: none; /* 禁止用户调整大小 */
            /* 修复滚动条与圆角冲突问题，同时保持滚动功能 */
            overflow-y: auto;
            overflow-x: hidden;
            position: relative;
        }

        #prompt:focus {
            border-color: #64b5f6;
            box-shadow: 0 0 0 3px rgba(33, 150, 243, 0.2);
        }
        
        #inputArea button {
            position: absolute;
            right: 25px;
            bottom: 25px;
            background-color: #e0e0e0;
            color: #666;
            border: none;
            border-radius: 50%;
            width: 36px;
            height: 36px;
            cursor: pointer;
            display: none;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            transition: all 0.3s ease;
            z-index: 10;
        }
        
        #inputArea button:hover {
            background-color: #4caf50;
            color: white;
            transform: scale(1.1);
        }
        
        #inputArea button:active {
            transform: scale(0.95);
        }
        
        #inputArea button.show {
            display: flex;
        }
        
        /* 特殊样式 - 发送按钮 */
        #send-btn {
            background-color: #4caf50;
            color: white;
        }
        
        #send-btn:hover {
            background-color: #45a049;
            transform: scale(1.1);
        }
        
        /* textarea 滚动条样式 */
        #prompt::-webkit-scrollbar {
            width: 6px;
        }

        #prompt::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 30px;
            margin: 10px 0; /* 与 textarea 圆角匹配 */
        }

        #prompt::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }

        #prompt::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }

        #chat pre {
            background: #f0f0f0;
            padding: 15px;
            border-radius: 8px;
            overflow: auto;
            word-wrap: break-word;
            word-break: break-all;
            margin: 10px 0;
        }

        #chat code {
            font-family: 'Courier New', Consolas, monospace;
            color: #d63384;
            word-wrap: break-word;
            word-break: break-all;
            background: #f8f9fa;
            padding: 2px 4px;
            border-radius: 4px;
        }

        #chat h1,
        #chat h2,
        #chat h3 {
            border-bottom: 1px solid #ddd;
            padding-bottom: 8px;
            margin: 15px 0;
            color: #333;
        }

        #chat li {
            list-style-type: none;
            padding-left: 0;
            margin-left: 0;
        }

        #chat ul li::before {
            content: "•";
            color: #64b5f6;
            display: inline-block;
            width: 1em;
            margin-left: -1em;
        }

        /* 正在思考中的动画 */
        .thinking {
            display: flex;
            align-items: center;
        }

        .dot {
            width: 8px;
            height: 8px;
            background-color: #999;
            border-radius: 50%;
            margin: 0 3px;
            animation: bounce 1.5s infinite;
        }

        .dot:nth-child(2) {
            animation-delay: 0.2s;
        }

        .dot:nth-child(3) {
            animation-delay: 0.4s;
        }

        @keyframes bounce {
            0%, 100% {
                transform: translateY(0);
            }
            50% {
                transform: translateY(-5px);
            }
        }


        /* 响应式设计 */
        @media (max-width: 1024px) {
            #container {
                width: 95%;
            }
        }

        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            
            .header-title {
                font-size: 24px;
            }
            
            #container {
                width: 95%;
                height: calc(100vh - 100px);
                flex-direction: column;
            }
            
            #sidebar {
                width: 100%;
                height: auto;
                border-right: none;
                border-bottom: 1px solid #ddd;
            }
        }

        /* 添加模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.4);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            border-radius: 8px;
            width: 300px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }

        #uploadModal .modal-content{
            width: 700px;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .modal-title {
            font-size: 18px;
            font-weight: bold;
        }

        .close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover {
            color: black;
        }

        .modal-body {
            margin-bottom: 20px;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .btn-primary {
            background-color: #4CAF50;
            color: white;
        }

        .btn-primary:hover {
            background-color: #45a049;
        }

        .btn-secondary {
            background-color: #ccc;
            color: black;
        }

        .btn-secondary:hover {
            background-color: #bbb;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        /* 会话模式标记样式 */
        .session-mode-tag {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 10px;
            font-weight: bold;
            margin-left: 5px;
            vertical-align: middle;
        }

        .session-mode-rag {
            background-color: #2196F3;
            color: white;
        }

        .session-mode-direct {
            background-color: #FF9800;
            color: white;
        }



    </style>
    <script src="./marked.min.js"></script>
</head>

<body>
    <h2 class="header-title">🤖 阿克苏AI助手</h2>


    <div id="container">
        <div id="sidebar">
            <button id="new-session-btn">+ 新建会话</button>
            <button id="config-btn">⚙️ 配置中心</button>
            <div id="sessions-list"></div>
        </div>
        <div id="main-content">
            <div id="chat"></div>
            <div id="inputArea">
                <textarea id="prompt" placeholder="请输入你的问题..."></textarea>
                <button id="send-btn" title="发送消息">➤</button>
                <button id="stop-btn" title="停止响应">⏹</button>
            </div>
        </div>
    </div>



    <!-- 创建会话模态框 -->
    <div id="createSessionModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <div class="modal-title">创建新会话</div>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="sessionName">会话名称:</label>
                    <input type="text" id="sessionName" value="新会话" />
                </div>
                <div class="form-group">
                    <label for="sessionMode">模式:</label>
                    <select id="sessionMode">
                        <option value="rag">RAG模式</option>
                        <option value="direct">直接模式</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" id="cancelSessionBtn">取消</button>
                <button class="btn btn-primary" id="confirmSessionBtn">确定</button>
            </div>
        </div>
    </div>

    <script>
        const chatDiv = document.getElementById("chat");
        const promptInput = document.getElementById("prompt");
        const sessionsList = document.getElementById("sessions-list");
        const newSessionBtn = document.getElementById("new-session-btn");
        const configBtn = document.getElementById("config-btn"); // 添加配置按钮
        const stopBtn = document.getElementById("stop-btn");
        const sendBtn = document.getElementById("send-btn");

        let sessions = {};
        let currentSessionId = null;
        let currentMessageController = null; // 用于控制当前消息流
        let currentThinkingElement = null; // 用于跟踪当前的思考元素

        // 页面加载时从服务端获取所有会话
        window.addEventListener("load", async () => {
            try {
                // 获取所有会话
                const response = await fetch("http://localhost:3000/sessions");
                if (response.ok) {
                    sessions = await response.json();
                    renderSessionsList();
                    
                    // 如果有会话，默认选择第一个
                    const sessionIds = Object.keys(sessions);
                    if (sessionIds.length > 0) {
                        switchToSession(sessionIds[0]);
                    }
                }
            } catch (err) {
                console.error("获取会话失败:", err);
            }
            // 初始状态设置在updateInputState中处理
            // 显示发送按钮
            sendBtn.classList.add("show");
        });


        // 渲染会话列表
        function renderSessionsList() {
            sessionsList.innerHTML = "";
            
            Object.values(sessions).forEach(session => {
                const sessionElement = document.createElement("div");
                sessionElement.className = `session-item ${session.id === currentSessionId ? 'active' : ''}`;
                sessionElement.dataset.sessionId = session.id;
                
                // 确定模式显示文本和样式
                const modeText = session.mode === "rag" ? "RAG" : "直接";
                const modeClass = session.mode === "rag" ? "session-mode-rag" : "session-mode-direct";
                
                sessionElement.innerHTML = `
                    <div class="session-item-header">
                        <div class="session-item-name" data-session-id="${session.id}">
                            ${session.name}
                            <span class="session-mode-tag ${modeClass}">${modeText}</span>
                        </div>
                        <button class="session-item-delete" data-session-id="${session.id}">×</button>
                    </div>
                    <div class="session-item-date">${formatDate(session.createdAt)}</div>
                `;
                
                sessionElement.addEventListener("click", (e) => {
                    // 如果点击的是删除按钮，不切换会话
                    if (e.target.classList.contains("session-item-delete")) {
                        return;
                    }
                    
                    // 如果点击的是会话名称，进入重命名模式
                    if (e.target.classList.contains("session-item-name")) {
                        enterRenameMode(session.id, e.target);
                        return;
                    }
                    
                    switchToSession(session.id);
                });
                
                sessionsList.appendChild(sessionElement);
            });
            
            // 为删除按钮添加事件监听器
            document.querySelectorAll(".session-item-delete").forEach(button => {
                button.addEventListener("click", (e) => {
                    e.stopPropagation();
                    const sessionId = button.dataset.sessionId;
                    deleteSession(sessionId);
                });
            });
            
            // 检查是否有会话，如果没有则禁用输入框
            updateInputState();
        }

        // 进入重命名模式
        function enterRenameMode(sessionId, element) {
            const session = sessions[sessionId];
            const originalName = session.name;
            
            // 创建输入框
            const input = document.createElement("input");
            input.type = "text";
            input.className = "session-rename-input";
            input.value = originalName;
            
            // 替换显示名称的元素为输入框
            element.replaceWith(input);
            input.focus();
            
            // 选择所有文本以便编辑
            input.select();
            
            // 处理回车键确认重命名
            input.addEventListener("keydown", (e) => {
                if (e.key === "Enter") {
                    e.preventDefault();
                    confirmRename(sessionId, input.value, input, element);
                }
                
                // 处理ESC键取消重命名
                if (e.key === "Escape") {
                    e.preventDefault();
                    e.stopPropagation();
                    cancelRename(input, element, originalName);
                }
            });
            
            // 处理失去焦点时确认重命名
            input.addEventListener("blur", (e) => {
                // 检查是否是因为点击输入框本身导致的blur事件
                if (e.relatedTarget === input) {
                    return;
                }
                confirmRename(sessionId, input.value, input, element);
            });
            
            // 阻止点击事件冒泡，防止触发父元素的点击事件
            input.addEventListener("click", (e) => {
                e.stopPropagation();
            });
            
            // 阻止mousedown事件冒泡
            input.addEventListener("mousedown", (e) => {
                e.stopPropagation();
            });
        }

        // 确认重命名
        function confirmRename(sessionId, newName, inputElement, originalElement) {
            // 恢复原来的元素
            inputElement.replaceWith(originalElement);
            
            // 如果名称为空或未更改，则不执行任何操作
            if (!newName.trim() || newName.trim() === sessions[sessionId].name) {
                originalElement.textContent = sessions[sessionId].name;
                return;
            }
            
            // 更新会话名称
            renameSession(sessionId, newName.trim());
            originalElement.textContent = newName.trim();
        }

        // 取消重命名
        function cancelRename(inputElement, originalElement, originalName) {
            inputElement.replaceWith(originalElement);
            originalElement.textContent = originalName;
        }

        // 格式化日期
        function formatDate(dateString) {
            const date = new Date(dateString);
            return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`;
        }

        // 切换到指定会话
        function switchToSession(sessionId) {
            // 如果当前有正在发送的消息，取消它
            if (currentMessageController) {
                currentMessageController.abort();
                currentMessageController = null;
            }
            
            currentSessionId = sessionId;
            const session = sessions[sessionId];
            session.history = session.history || [];
            renderHistory();
            renderSessionsList();
        }

        // 创建新会话
        async function createNewSession() {
            try {
                console.log("创建新会话按钮被点击");
                // 显示模态框
                const modal = document.getElementById("createSessionModal");
                const sessionNameInput = document.getElementById("sessionName");
                const sessionModeSelect = document.getElementById("sessionMode");
                
                if (!modal || !sessionNameInput || !sessionModeSelect) {
                    console.error("模态框元素未找到");
                    return;
                }
                
                // 设置默认值
                sessionNameInput.value = "新会话";
                sessionModeSelect.value = "rag";
                
                modal.style.display = "block";
                console.log("模态框已显示");
            } catch (error) {
                console.error("创建会话时出错:", error);
            }
        }

        // 确认创建会话
        async function confirmCreateSession() {
            try {
                console.log("确认创建会话按钮被点击");
                const sessionNameInput = document.getElementById("sessionName");
                const sessionModeSelect = document.getElementById("sessionMode");
                const modal = document.getElementById("createSessionModal");
                
                if (!sessionNameInput || !sessionModeSelect || !modal) {
                    console.error("模态框元素未找到");
                    return;
                }
                
                const sessionName = sessionNameInput.value.trim() || "新会话";
                const sessionMode = sessionModeSelect.value;
                
                console.log("会话信息:", { sessionName, sessionMode });
                
                const response = await fetch("http://localhost:3000/sessions", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ 
                        name: sessionName,
                        mode: sessionMode
                    })
                });
                
                if (response.ok) {
                    const newSession = await response.json();
                    console.log("新会话创建成功:", newSession);
                    sessions[newSession.id] = newSession;
                    switchToSession(newSession.id);
                    renderSessionsList();
                    
                    // 启用输入框并聚焦
                    promptInput.disabled = false;
                    promptInput.placeholder = "请输入你的问题...";
                    promptInput.title = "";
                    promptInput.focus();
                } else {
                    console.error("创建会话失败，HTTP状态码:", response.status);
                }
            } catch (err) {
                console.error("创建会话失败:", err);
            } finally {
                // 隐藏模态框
                const modal = document.getElementById("createSessionModal");
                if (modal) {
                    modal.style.display = "none";
                }
            }
        }

        // 取消创建会话
        function cancelCreateSession() {
            try {
                console.log("取消创建会话按钮被点击");
                const modal = document.getElementById("createSessionModal");
                if (modal) {
                    modal.style.display = "none";
                }
            } catch (error) {
                console.error("取消创建会话时出错:", error);
            }
        }

        // 删除会话
        async function deleteSession(sessionId) {
            if (Object.keys(sessions).length <= 1) {
                alert("至少需要保留一个会话");
                return;
            }
            
            if (confirm("确定要删除这个会话吗？")) {
                try {
                    const response = await fetch(`http://localhost:3000/sessions/${sessionId}`, {
                        method: "DELETE"
                    });
                    
                    if (response.ok) {
                        delete sessions[sessionId];
                        
                        // 如果删除的是当前会话，切换到第一个会话
                        if (currentSessionId === sessionId) {
                            const sessionIds = Object.keys(sessions);
                            if (sessionIds.length > 0) {
                                switchToSession(sessionIds[0]);
                            }
                        }
                        
                        renderSessionsList();
                    }
                } catch (err) {
                    console.error("删除会话失败:", err);
                }
            }
        }

        // 重命名会话
        function renameSession(sessionId, newName) {
            sessions[sessionId].name = newName;
            updateSession(sessionId);
        }

        // 获取当前会话的历史记录
        function getCurrentSessionHistory() {
            if (!currentSessionId || !sessions[currentSessionId]) {
                return [];
            }
            return sessions[currentSessionId].history || [];
        }

        // 更新会话到服务端
        async function updateSession(sessionId) {
            try {
                const session = sessions[sessionId];
                await fetch(`http://localhost:3000/sessions/${sessionId}`, {
                    method: "PUT",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ history: session.history, name: session.name })
                });
                renderSessionsList();
            } catch (err) {
                console.error("更新会话失败:", err);
            }
        }

        // 更新输入框状态（启用/禁用）
        function updateInputState() {
            const hasSessions = Object.keys(sessions).length > 0;
            
            if (hasSessions) {
                promptInput.disabled = false;
                promptInput.placeholder = "请输入你的问题...";
                promptInput.title = ""; // 清除提示
            } else {
                promptInput.disabled = true;
                promptInput.placeholder = "请创建新会话...";
                promptInput.title = "请先创建新会话";
            }
        }

        function renderHistory() {
            // 清空聊天区域
            chatDiv.innerHTML = "";
            
            // 渲染历史记录
            const history = getCurrentSessionHistory();
            history.forEach(item => {
                if (item.role === "user") {
                    appendMessage("你", item.content, "user");
                } else if (item.role === "assistant") {
                    appendMessage("AI助手", item.content, "assistant");
                }
            });
        }

        function appendMessage(sender, content, role) {
            const msg = document.createElement("div");
            msg.className = "message " + role;
            msg.innerHTML = `<strong>${sender}:</strong> <br/> ${marked.parse(
                content || ""
            )}`;
            chatDiv.appendChild(msg);
            chatDiv.scrollTop = chatDiv.scrollHeight;
        }

        // 创建正在思考中的动画元素
        function createThinkingElement() {
            const thinkingDiv = document.createElement("div");
            thinkingDiv.className = "thinking";
            thinkingDiv.innerHTML = `
                <span>正在思考中</span>
                <div class="dot"></div>
                <div class="dot"></div>
                <div class="dot"></div>
            `;
            return thinkingDiv;
        }

        async function sendMessage() {
            const prompt = promptInput.value.trim();
            if (!prompt) return;

            // 创建一个AbortController用于取消请求
            const controller = new AbortController();
            currentMessageController = controller;
            
            const currentSessionBeforeSend = currentSessionId;
            
            appendMessage("你", prompt, "user");
            promptInput.value = "";

            // 限制历史记录数量，只保留最近的10条消息（5轮对话）
            const MAX_HISTORY_LENGTH = 10;
            const history = getCurrentSessionHistory();
            const recentHistory = history.slice(-MAX_HISTORY_LENGTH);
            
            // 切换按钮：显示停止按钮，隐藏发送按钮
            sendBtn.classList.remove("show");
            stopBtn.classList.add("show");
            
            // 创建助手回答占位
            const msgElem = document.createElement("div");
            msgElem.className = "message assistant";
            
            // 添加正在思考中的动画
            const thinkingElem = createThinkingElement();
            currentThinkingElement = thinkingElem; // 跟踪当前思考元素
            msgElem.innerHTML = `<strong>AI助手:</strong> <br/>`;
            msgElem.appendChild(thinkingElem);
            
            chatDiv.appendChild(msgElem);
            chatDiv.scrollTop = chatDiv.scrollHeight;

            // 保留历史副本，避免被修改
            const localHistory = [...recentHistory, { role: "user", content: prompt }];
            
            try {
                // 获取当前会话的模式
                const currentSession = sessions[currentSessionId];
                const mode = currentSession.mode || "rag"; // 默认为RAG模式
                
                let enhancedPrompt = prompt;
                let requestBody = { prompt: enhancedPrompt };
                
                // 只在RAG模式下执行向量搜索
                if (mode === "rag") {
                    // 首先尝试在向量数据库中搜索相关信息
                    const vectorResponse = await fetch("http://localhost:3000/vector-search", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({ query: prompt })
                    });
                    
                    let context = "";
                    if (vectorResponse.ok) {
                        const results = await vectorResponse.json();
                        if (results.length > 0) {
                            context = "基于以下文档内容:\n" + results.map(r => r.content).join("\n---\n");
                        }
                    }
                    
                    // 构造包含上下文的提示
                    enhancedPrompt = context ? `${context}\n\n请根据以上文档内容回答问题: ${prompt}` : prompt;
                    requestBody = { prompt: enhancedPrompt };
                } else {
                    // 在非RAG模式下传递历史记录
                    requestBody = { prompt: enhancedPrompt, history: localHistory };
                }
                
                const res = await fetch("http://localhost:3000/chat-stream", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify(requestBody),
                    signal: controller.signal
                });

                // 移除正在思考中的动画
                if (thinkingElem.parentNode) {
                    thinkingElem.parentNode.removeChild(thinkingElem);
                }
                currentThinkingElement = null; // 清除思考元素引用

                const reader = res.body.getReader();
                const decoder = new TextDecoder();
                let full = "";
                const streamingElem = document.createElement("div");
                streamingElem.className = "streaming";
                msgElem.appendChild(streamingElem);

                // 用于跟踪上一次处理的完整块
                let lastProcessedChunk = "";
                
                while (true) {
                    // 检查会话是否在流处理过程中被切换
                    if (currentSessionId !== currentSessionBeforeSend) {
                        reader.cancel();
                        break;
                    }
                    
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    full += chunk;

                    // 实时渲染Markdown，而不是等到全部完成
                    try {
                        streamingElem.innerHTML = marked.parse(full);
                    } catch (e) {
                        // 如果解析失败，先显示纯文本
                        streamingElem.textContent = full;
                    }
                    
                    chatDiv.scrollTop = chatDiv.scrollHeight;
                }

                // 如果会话在处理过程中被切换，则不更新历史记录
                if (currentSessionId !== currentSessionBeforeSend) {
                    return;
                }

                // 确保最终内容正确渲染
                try {
                    streamingElem.innerHTML = marked.parse(full);
                } catch (e) {
                    streamingElem.textContent = full;
                }

                // 更新历史，但限制长度
                const currentHistory = getCurrentSessionHistory();
                currentHistory.push({ role: "user", content: prompt });
                currentHistory.push({ role: "assistant", content: full });
                
                // 确保历史记录不会无限增长
                if (currentHistory.length > MAX_HISTORY_LENGTH) {
                    const trimmedHistory = currentHistory.slice(-MAX_HISTORY_LENGTH);
                    sessions[currentSessionId].history = trimmedHistory;
                } else {
                    sessions[currentSessionId].history = currentHistory;
                }
                
                // 保存历史记录到服务端
                if (currentSessionId) {
                    updateSession(currentSessionId);
                }
            } catch (error) {
                // 如果是由于切换会话导致的取消，不显示错误
                if (error.name === 'AbortError' || currentSessionId !== currentSessionBeforeSend) {
                    return;
                }
                
                // 移除正在思考中的动画
                if (thinkingElem.parentNode) {
                    thinkingElem.parentNode.removeChild(thinkingElem);
                }
                currentThinkingElement = null; // 清除思考元素引用
                
                // 显示错误消息
                const errorElem = document.createElement("div");
                errorElem.className = "streaming";
                errorElem.textContent = "抱歉，出现了一些问题，请稍后重试。";
                msgElem.appendChild(errorElem);
                console.error("发送消息时出错:", error);
            } finally {
                // 切换按钮：隐藏停止按钮，显示发送按钮
                stopBtn.classList.remove("show");
                sendBtn.classList.add("show");
                
                // 清理当前消息控制器
                if (currentMessageController === controller) {
                    currentMessageController = null;
                }
                currentThinkingElement = null; // 清除思考元素引用
            }
        }

        // 停止响应函数
        function stopResponse() {
            if (currentMessageController) {
                currentMessageController.abort();
                currentMessageController = null;
                
                // 切换按钮：隐藏停止按钮，显示发送按钮
                stopBtn.classList.remove("show");
                sendBtn.classList.add("show");
                
                // 如果有正在思考的元素，移除它
                if (currentThinkingElement && currentThinkingElement.parentNode) {
                    // 创建一个提示文本替代思考动画
                    const stoppedText = document.createElement("div");
                    stoppedText.className = "streaming";
                    stoppedText.textContent = "[响应已停止]";
                    currentThinkingElement.parentNode.replaceChild(stoppedText, currentThinkingElement);
                    currentThinkingElement = null;
                }
            }
        }

        promptInput.addEventListener("keydown", (e) => {
            if (e.key === "Enter" && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // 新建会话按钮事件
        newSessionBtn.addEventListener("click", createNewSession);
        
        // 配置按钮事件
        configBtn.addEventListener("click", jumpToKnowledgeControl);
        
        // 停止按钮事件
        stopBtn.addEventListener("click", stopResponse);
        
        // 发送按钮事件
        sendBtn.addEventListener("click", sendMessage);

        // 页面加载完成后自动聚焦到输入框
        window.addEventListener("load", () => {
            promptInput.focus();
        });

        // 模态框事件监听器
        document.getElementById("confirmSessionBtn").addEventListener("click", confirmCreateSession);
        document.getElementById("cancelSessionBtn").addEventListener("click", cancelCreateSession);
        
        // 点击关闭按钮关闭模态框
        document.querySelector("#createSessionModal .close").addEventListener("click", cancelCreateSession);
        

        // 点击模态框外部关闭模态框
        window.addEventListener("click", (event) => {
            const createSessionModal = document.getElementById("createSessionModal");
            const uploadModal = document.getElementById("uploadModal");
            if (event.target === createSessionModal) {
                createSessionModal.style.display = "none";
            }
            if (event.target === uploadModal) {
                uploadModal.style.display = "none";
            }
        });

        // 按ESC键关闭模态框
        window.addEventListener("keydown", (event) => {
            if (event.key === "Escape") {
                const createSessionModal = document.getElementById("createSessionModal");
                const uploadModal = document.getElementById("uploadModal");
                if (createSessionModal.style.display === "block") {
                    createSessionModal.style.display = "none";
                }
                if (uploadModal.style.display === "block") {
                    uploadModal.style.display = "none";
                }
            }
        });

        // 打开配置模态框
        // function openConfigModal() {
        //     const modal = document.getElementById("uploadModal");
        //     modal.style.display = "block";
            
        //     // 清空之前的结果
        //     const resultDiv = document.getElementById("upload-result");
        //     resultDiv.style.display = "none";
        // }

        function jumpToKnowledgeControl(){
            window.location.href = "knowledgeControl.html";
        }


    </script>
</body>

</html>